import { Piece, PieceProps, PieceAnalysis } from '@/types/piece'

export const DEFAULT_SCORE_COUNT = 9
export const JEWEL_SCORE_COUNT = 15

/**
 * 计算总分
 * 按props分类，返回list
 * [0, 1, 2]
 * @param pieces
 * @param storePieceProps
 * @param scoreCount
 * @returns PieceAnalysis[]
 */
export function calculateTotalScore(
  pieces: (Piece | undefined)[],
  storePieceProps: Record<number, PieceProps>,
  scoreCount: number
): PieceAnalysis[] {
  const prop2Analysis: Record<number, PieceAnalysis> = {}
  pieces.forEach((piece, index) => {
    if (!piece || !piece.props) return
    const idx = Math.floor(index / 5)
    const props_ids = piece.props.split(',').map((id) => parseInt(id.trim()))
    for (const id of props_ids) {
      const prop = storePieceProps[id]
      const scores = Array(scoreCount).fill(undefined)
      scores[idx] = piece.score
      if (prop) {
        if (!prop2Analysis[id]) {
          prop2Analysis[id] = {
            id,
            title: prop.describe,
            scores: scores,
            result: 0,
            effect: prop.levels
          }
        } else {
          if (typeof prop2Analysis[id].scores[idx] === 'number') {
            prop2Analysis[id].scores[idx] += piece.score
          } else {
            prop2Analysis[id].scores[idx] = piece.score
          }
        }
        prop2Analysis[id].result += piece.score
      }
    }
  })
  const result = Object.values(prop2Analysis).sort(
    (a, b) => b.result - a.result
  )
  return result
}

export function calResultEffect(val: number, levels: string): string {
  if (!levels || levels.length === 0) return ''
  const levelArray = levels.split(',')
  if (levelArray.length < 10) return ''
  const hasUnit = levelArray.length > 11 && isNaN(Number(levelArray[11]))
  const unit = hasUnit ? levelArray[11] : ''
  if (val >= 100) {
    return levelArray[10] + unit
  }
  const index = Math.floor(val / 10)
  const res = levelArray[index]
  return res + unit
}
